package com.kmu.kmucampus.Fragment;


import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ExpandableListView;
import android.widget.ListView;
import android.widget.Toast;

import com.kmu.kmucampus.R;
import com.kmu.kmucampus.activity.MainActivity;
import com.kmu.kmucampus.adapter.treeViewAdapter.ParentAdapter;
import com.kmu.kmucampus.adapter.treeViewAdapter.TreeListViewAdapter;
import com.kmu.kmucampus.treeView.ChildEntity;
import com.kmu.kmucampus.treeView.ParentEntity;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import mytest.ssw.www.api.ActionCallbackListener;
import mytest.ssw.www.api.ApiResponse;
import mytest.ssw.www.core.DeptNodeCore;
import mytest.ssw.www.core.sqLiteTools;
import mytest.ssw.www.mylibrary.Contents;
import mytest.ssw.www.mylibrary.DeptNode;


/**
 * Created by Administrator on 2016/3/26 0026.
 */
public class AddrBookFragment extends Fragment implements
        ExpandableListView.OnGroupExpandListener,
        ParentAdapter.OnChildTreeViewClickListener
{
    public final static String FRAGMENT_PARAM = "fragment";
    // ProgressDialog progressDialog;
    private String TAG = AddrBookFragment.class.getName();
    private Context mContext;
    private ExpandableListView eList;
    sqLiteTools sqlTool;
    private ArrayList<ParentEntity> parents;
    private ParentAdapter adapter;
    final  String TB_DEPT="TB_DEPT";
    final  String TB_STU="TB_STU";
    List<DeptNode> deptList;
    private View vw;
    DeptNodeCore deptnodecore;
    private List<DeptNode> mDatas;
    private ListView mTree;
    private TreeListViewAdapter mAdapter;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragmentaddrbook, container, false);
        mContext = getContext();
        vw = view;
        Log.i(TAG, "--------AddrFragmentCreatView");
        setAddressBook();
        return view;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        sqlTool = new sqLiteTools(getActivity().getFilesDir().toString());
        if (savedInstanceState != null) {
            Log.d("Addr-create", "save is not null");
        }
        super.onCreate(savedInstanceState);
    }

    public void setAddressBook() {
        final sqLiteTools sqlTools = new sqLiteTools(getActivity().getFilesDir().toString());
        deptList = sqlTools.getDeptfoFrDB(TB_DEPT);
        Log.d("initDept_fileDir1",""+getActivity().getFilesDir().toString()+TB_DEPT);
        String CONNECT_TYPE = ((MainActivity) getActivity()).appAction.getNetworkInfo(getContext());
        Log.d("CONNECT_TYPE", "" + CONNECT_TYPE);
        if ( deptList.size() == 0) {
            Log.d("DeptNodeSizeFromNet","setAddressBook_"+deptList.size());
            ((MainActivity) getActivity()).appAction.GetDeptNodeList(new ActionCallbackListener<List<DeptNode>>() {
                @Override
                public void onSuccess(List<DeptNode> data) {
                    loadData(data);
                    initEList();
                    sqlTools.insertDetp(TB_DEPT, data);
                    List<DeptNode> deptList = sqlTool.getDeptfoFrDB(TB_DEPT);
                    Log.d("DeptNodeCount1", "" + deptList.size());
                }
                @Override
                public void onFailure(String errorEvent, String element) {
                    //     progressDialog.dismiss();
                    Toast.makeText(getActivity(), errorEvent, Toast.LENGTH_SHORT).show();
                }
            });
        }
        else{
            Log.d("DeptNodeSizeFromDB",""+deptList.size());
            if (deptList.size() > 0) {
                loadData(deptList);
                initEList();
            }
        }
    }
    public void switchContent(Fragment from, Fragment to) {
        if (from != to) {
            FragmentTransaction transaction = getActivity().getSupportFragmentManager()
                    .beginTransaction();
            if (!to.isAdded()) {
                // 隐藏当前的fragment，add下一个到Activity中
                transaction.add(R.id.fragment, to).show(to).commit();
            } else {
                // 隐藏当前的fragment，显示下一个
                transaction.show(to).commit();
            }
        }
    }

    /**
     * 点击子ExpandableListView的子项时，回调本方法，根据下标获取值来做相应的操作
     * Toast.makeText(
     * mContext,
     * "点击的下标为： parentPosition=" + parentPosition
     * + "   groupPosition=" + groupPosition
     * + "   childPosition=" + childPosition + "\n点击的是："
     * + childNum, Toast.LENGTH_SHORT).show();
     */
    @Override
    public void onClickPosition(int parentPosition, int groupPosition,
                                int childPosition) {
        // do something
        String childNum = parents.get(parentPosition).getChilds()
                .get(groupPosition).getChildNums().get(childPosition)
                .toString();
        Log.d("Click", childNum);
        if(childNum.contains("BM")) {
            AddrDetailFragment addrFragment = new AddrDetailFragment();
            Bundle b = getActivity().getIntent().getExtras();
            b.putString("deptNo", childNum);
            addrFragment.setArguments(b);
            switchContent(this, addrFragment);
            Log.d("addrFG", "JUMP");
        }
        else {
            if(childNum!=null) {
                Intent intent = new Intent(Intent.ACTION_CALL, Uri.parse("tel:" + childNum));
                startActivity(intent);
            }
            else {Toast.makeText(getActivity(), "电话号码为空！", Toast.LENGTH_SHORT).show();}
        }
    }

    /**
     * 展开一项，关闭其他项，保证每次只能展开一项
     */
    @Override
    public void onGroupExpand(int groupPosition) {
        for (int i = 0; i < parents.size(); i++) {
            if (i != groupPosition) {
                //  eList.collapseGroup(i);
                Log.d("onGroupExpand"+Integer.toString(parents.size()),Integer.toString(groupPosition)+"-pos:"+Integer.toString(i));
            }
        }
    }

    public List<DeptNode> getNodesByLevelAndNum(int level, String num, List<DeptNode> nodeList) {
        List<DeptNode> result = new ArrayList<DeptNode>();
        for (int i = 0; i < nodeList.size(); i++) {
            if (nodeList.get(i).getLevel() == level)
                if (nodeList.get(i).getNum().contains(num))
                    result.add(nodeList.get(i));
        }
        return result;
    }

    private void loadData(List<DeptNode> inList) {
        int i, j, k;
        Log.d("inList_size", Integer.toString(inList.size()));
        List<DeptNode> node1 = getNodesByLevelAndNum(2, "BM_01_02", inList);
        List<DeptNode> teacherNode=getTeacherInfo("BM_01_01");
        if(teacherNode!=null)inList.addAll(teacherNode);
        Log.d("inList_size_2", Integer.toString(inList.size()));
        node1.addAll(getNodesByLevelAndNum(1, "BM_01_01", inList));
        parents = new ArrayList<ParentEntity>();
        for (i = 0; i < node1.size(); i++)
        {
            ParentEntity parent = new ParentEntity();
            parent.setGroupName("" + node1.get(i).getName());
            parent.setGroupColor(Color.parseColor("#000000"));
            ArrayList<ChildEntity> childs = new ArrayList<ChildEntity>();
            List<DeptNode> node2 = getNodesByLevelAndNum(node1.get(i).getLevel() + 1, node1.get(i).getNum(), inList);
            for (j = 0; j < node2.size(); j++) {
                ChildEntity child = new ChildEntity();
                child.setGroupName(node2.get(j).getName());
                child.setGroupColor(Color.parseColor("#000000"));
                ArrayList<String> childNames = new ArrayList<String>();
                ArrayList<String> childNums = new ArrayList<String>();
                 Log.d("loadData:",node2.get(j).getNum());
                List<DeptNode> node3;
                node3 = getNodesByLevelAndNum(node2.get(j).getLevel() + 1, node2.get(j).getNum(), inList);
             //   Log.d("loadData2:", node3.get(0).getName() + "---" + node3.get(k).getName());
               /* if (node2.get(j).getLevel() == 2 && node3.size()==0) {
                    node3=null;
                    node3=getTeacherInfo(node2.get(j).getNum());
                    Log.d("loadData2:", node3.get(0).getName() + "---" + node3.size());
                }*/
                for (k = 0; k < node3.size(); k++) {
                    Log.d("loadData3:", node2.get(j).getNum() + "---" + node3.get(k).getName());
                    childNames.add(node3.get(k).getName());
                    if(node3.get(k).getLevel()==3){childNums.add(node3.get(k).getpNum());}
                    else  childNums.add(node3.get(k).getNum());
                }
                child.setChildNames(childNames);
                child.setChildNums(childNums);
                childs.add(child);
            }
            parent.setChilds(childs);
            parents.add(parent);
        }
    }

    public List<DeptNode> getTeacherInfo(String BMnum) {
        int i;
        List<DeptNode> deptList=new ArrayList<>();
        HashMap<String, String> deptBm = new HashMap<>();
        List<Contents> datas=sqlTool.getTeacherInfoFrDB(TB_STU,BMnum);
        Log.d("getTeacherInfo","-----"+TB_STU+"----"+TB_STU);
        String CONNECT_TYPE = ((MainActivity) getActivity()).appAction.getNetworkInfo(getContext());
        Log.d("CONNECT_TYPE", "" + CONNECT_TYPE);
        if ( datas.size() == 0 || CONNECT_TYPE=="WIFI") {
            datas=null;
            deptBm.put("departmentNum", BMnum);
            datas = ((MainActivity) getActivity()).appAction.SearchInfor(deptBm, new ActionCallbackListener<ApiResponse<List<Contents>>>() {
                @Override
                public void onSuccess(ApiResponse<List<Contents>> data) {
                    Log.d("GetTinfo",Integer.toString( data.getContents().size()));
                         for(int i=0;i<data.getContents().size();i++) {
                         Log.d("GetTinfoFromNet", Integer.toString(data.getContents().size()));
                        sqlTool.insertTeacherInfo(TB_STU, data.getContents().get(i));
                    }
                }
                @Override
                public void onFailure(String errorEvent, String message) {
                }
            });
        }
            Log.d("GetTinfo", Integer.toString(datas.size()));
            for (i = 0; i < datas.size(); i++) {
                DeptNode dpnode = new DeptNode();
                dpnode.setName(datas.get(i).getName() + "老师");
                dpnode.setNum(datas.get(i).getDepartmentNum());   //
               dpnode.setpNum(datas.get(i).getPhoneNum());
                dpnode.setLevel(3);
                deptList.add(dpnode);
                Log.d("GetTinfo", dpnode.getName()+"----"+dpnode.getLevel());
            }
        if(deptList.size()==0) {
            return null;
        }
        else   {
            Log.d("deptList_size", Integer.toString(deptList.size()));
            return  deptList;
        }
    }

    private void initEList() {
        eList = (ExpandableListView) vw.findViewById(R.id.addrbook_List);
        eList.setOnGroupExpandListener(this);
        adapter = new ParentAdapter(mContext, parents);
        eList.setAdapter(adapter);
        adapter.setOnChildTreeViewClickListener(this);

    }

}

/*
 ListAdapter myAdapter = new SimpleAdapter(getActivity(),getdata(data),
                        R.layout.layout_listitem,
                        new String[]{"name"},
                        new int[]{R.id.tv_titleKey}
                );
    private FragmentManager fm;
    private AddrBookFragment addr;
    private NoticeFragment notice;
    private SettingFragment settings;
    private AddrDetailFragment detail;
  if(savedInstanceState!=null)
        {
             addr=(AddrBookFragment) fm.findFragmentByTag("addr");
             notice=(NoticeFragment) fm.findFragmentByTag("notice");
             settings=(SettingFragment) fm.findFragmentByTag("settings");
             detail=(AddrDetailFragment) fm.findFragmentByTag("detail");
            Log.d("addrFG","saveInstance");
        }

          progressDialog=new ProgressDialog(view.getContext());
        progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
        Window window = progressDialog.getWindow();
        WindowManager.LayoutParams lp = window.getAttributes();
        lp.alpha = 100f;// 透明度
        lp.dimAmount = 0.8f;// 黑暗度
        window.setAttributes(lp);
        progressDialog.setCancelable(true);
        progressDialog.setIndeterminate(true);
        progressDialog.setTitle("加载信息");
        progressDialog.setMessage("正在加载....");
        progressDialog.setIndeterminate(false);
        progressDialog.setCancelable(true);
        //     progressDialog.setButton("取消", new Bt1DialogListener());
       // progressDialog.show();

* */